package com.auto.base.util

import com.google.gson.Gson
import com.google.gson.JsonSyntaxException
import com.google.gson.reflect.TypeToken

/**
 * Created by YuanWei1 on 2025/6/16.
 *
 * Description:
 */
object GsonUtil {
    val gson: Gson = Gson()

    // 任意对象转 JSON 字符串
    fun toJson(obj: Any?): String {
        return gson.toJson(obj)
    }

    // JSON 字符串转对象
    inline fun <reified T> fromJson(json: String?): T? {
        return try {
            gson.fromJson(json, T::class.java)
        } catch (e: JsonSyntaxException) {
            e.printStackTrace()
            null
        }
    }

    // JSON 字符串转 List<T>
    inline fun <reified T> fromJsonList(json: String?): List<T>? {
        return try {
            val type = object : TypeToken<List<T>>() {}.type
            gson.fromJson(json, type)
        } catch (e: JsonSyntaxException) {
            e.printStackTrace()
            null
        }
    }

    // JSON 字符串转 Map<String, Any>
    fun fromJsonToMap(json: String?): Map<String, Any>? {
        return try {
            val type = object : TypeToken<Map<String, Any>>() {}.type
            gson.fromJson(json, type)
        } catch (e: JsonSyntaxException) {
            e.printStackTrace()
            null
        }
    }
}